package com.bappi.utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.bappi.ui.ChartData;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import static android.provider.BaseColumns._ID;

public class DatabaseAccessor {

	public static DatabaseHelper myDbHelper = null;
	public static SQLiteDatabase rdb = null;
	public static SQLiteDatabase wdb = null;

	public static synchronized final void initDB(Context context)
			throws Exception {
		if (myDbHelper == null) {
			myDbHelper = new DatabaseHelper(context);
			// myDbHelper.createDataBase();
			rdb = myDbHelper.getReadableDatabase();
			wdb = myDbHelper.getWritableDatabase();
		}
	}

	public static synchronized final void closeDB() {
		if (myDbHelper != null) {
			myDbHelper.close();
			rdb.close();
			wdb.close();
			myDbHelper = null;
			rdb = null;
			wdb = null;
		}
	}

	public static final int getTimestamp(long milli) {
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(milli);
		return (cal.get(Calendar.YEAR) * 1000) + cal.get(Calendar.DAY_OF_YEAR);
	}

	public static final int getTimestamp() {
		return getTimestamp(System.currentTimeMillis());
	}

	public static final Date getDataFromTimestamp(int timestamp) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.MILLISECOND, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.DAY_OF_YEAR, timestamp % 1000);
		cal.set(Calendar.YEAR, timestamp / 1000);
		return cal.getTime();
	}

	
	public static void saveCalories(int value) {
		save(DatabaseHelper.TABLE_NAME_1, value);
	}
	public static void saveUnit(int value) {
		save(DatabaseHelper.TABLE_NAME_2, value);
	}
	public static void saveActivities(int value) {
		save(DatabaseHelper.TABLE_NAME_3, value);
	}
	public static void saveWeight(int value) {
		save(DatabaseHelper.TABLE_NAME_4, value);
	}

	private static void save(String tableName, int value) {
		try {
			int timestamp = getTimestamp();
			String qry = "SELECT " + _ID + " FROM " + tableName
					+ " WHERE time = " + timestamp;
			Cursor cursor = rdb.rawQuery(qry, null);
			long dataId = -1;
			boolean dataFound = false;
			if (cursor.moveToNext()) {
				dataFound = true;
				dataId = cursor.getLong(0);
			}
			cursor.close();

			if (dataFound) {
				ContentValues values = new ContentValues();
				values.put("time", timestamp);
				values.put("value", value);
				wdb.update(tableName, values, _ID + "=" + dataId, null);
			} else {
				ContentValues values = new ContentValues();
				values.put("time", timestamp);
				values.put("value", value);
				wdb.insertOrThrow(tableName, null, values);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static int getCaloriesValue() {
		return get(DatabaseHelper.TABLE_NAME_1);
	}
	public static int getUnitValue() {
		return get(DatabaseHelper.TABLE_NAME_2);
	}
	public static int getActivitiesValue() {
		return get(DatabaseHelper.TABLE_NAME_3);
	}
	public static int getWeightValue() {
		return get(DatabaseHelper.TABLE_NAME_4);
	}
	
	private static int get(String tableName) {
		int ret = 0;
		try {
			int timestamp = getTimestamp();
			String qry = "SELECT value FROM " + tableName
					+ " WHERE time = " + timestamp;
			Cursor cursor = rdb.rawQuery(qry, null);
			if (cursor.moveToNext()) {
				ret = cursor.getInt(0);
			}
			cursor.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}
	public static List<ChartData> getCaloriesValue(int startTimestamp,int endTimestamp) {
		return get(DatabaseHelper.TABLE_NAME_1,startTimestamp,endTimestamp);
	}
	public static List<ChartData> getUnitValue(int startTimestamp,int endTimestamp) {
		return get(DatabaseHelper.TABLE_NAME_2,startTimestamp,endTimestamp);
	}
	public static List<ChartData> getActivitiesValue(int startTimestamp,int endTimestamp) {
		return get(DatabaseHelper.TABLE_NAME_3,startTimestamp,endTimestamp);
	}
	public static List<ChartData> getWeightValue(int startTimestamp,int endTimestamp) {
		return get(DatabaseHelper.TABLE_NAME_4,startTimestamp,endTimestamp);
	}
	private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd");
	private static List<ChartData> get(String tableName,int startTimestamp,int endTimestamp) {
		List<ChartData> ret = new ArrayList<ChartData>();
		try {
			String qry = "SELECT value,time FROM " + tableName
					+ " WHERE time >= " + startTimestamp+" AND time <= "+endTimestamp +" ORDER BY time ASC ";
			Cursor cursor = rdb.rawQuery(qry, null);
			while (cursor.moveToNext()) {
				ret.add(new ChartData(SDF.format(getDataFromTimestamp(cursor.getInt(1))), cursor.getInt(0)));
			}
			cursor.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	// public static List<Vocab> getVocabList() {
	// List<Vocab> ret = new ArrayList<Vocab>();
	// try {
	// String[] columns = { "id", "listName", "listBit" };
	// String tableName = "Lists";
	// Cursor cursor = rdb.query(tableName, columns, null, null, null,
	// null, null);
	// while (cursor.moveToNext()) {
	// ret.add(new Vocab(cursor.getString(0), cursor.getString(1),
	// cursor.getString(2)));
	// }
	// cursor.close();
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// return ret;
	// }
	//
	// public static int getAvailableCredit() {
	// return (getTotalCredit()-getConsumedCredit());
	// }
	//
	// public static int getTotalCredit() {
	// int ret = 0;
	// try {
	// String qry = "SELECT COUNT(*) FROM credit WHERE creditType = "
	// + Constants.CREDIT_TYPE_FULL;
	// Cursor cursor = rdb.rawQuery(qry, null);
	// if (cursor.moveToNext()) {
	// if (cursor.getInt(0) > 0) {
	// ret = Constants.FULL_CREDIT_VALUE;
	// }
	// }
	// cursor.close();
	// if (ret != Constants.FULL_CREDIT_VALUE) {
	// qry = "SELECT ifnull(SUM(creditValue),0)  FROM credit WHERE creditType ="
	// + Constants.CREDIT_TYPE_PARTIAL;
	// cursor = rdb.rawQuery(qry, null);
	// if (cursor.moveToNext()) {
	// ret = cursor.getInt(0);
	// }
	// cursor.close();
	// }
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// return ret;
	// }
	// public static int getConsumedCredit() {
	// int ret = 0;
	// try {
	// String qry =
	// "SELECT ifnull(SUM(creditValue),0)  FROM credit WHERE creditType = "
	// + Constants.CREDIT_TYPE_CONSUMED;
	// Cursor cursor = rdb.rawQuery(qry, null);
	// if (cursor.moveToNext()) {
	// ret = cursor.getInt(0);
	// }
	// cursor.close();
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// return ret;
	// }
	//
	// public static void addCredit(int creditValue, int creditType) {
	// try {
	// String tableName = "credit";
	// ContentValues values = new ContentValues();
	// values.put("creditType", creditType);
	// values.put("creditValue", creditValue);
	// wdb.insertOrThrow(tableName, null, values);
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }

}
